/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.connector.server;

import com.je.common.base.message.vo.PushMessage;
import com.je.connector.base.config.InstantConfig;
import com.je.connector.base.connection.registry.ConnectionRegistry;
import com.je.connector.rpc.ConnectionRegistryRpcService;
import com.je.connector.server.listener.DefaultTopicListener;
import com.je.connector.server.registry.ClusterRedisConnectionRegistry;
import com.je.connector.server.listener.TopicListenerContainer;
import com.je.connector.service.PushService;
import com.je.connector.server.timer.HandshakeCheckTimer;
import com.je.connector.server.prototype.WebSocketServer;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 即时通讯服务门面
 *
 * @ProjectName: instant-message
 * @Package: com.connector.server
 * @ClassName: InstantServer
 * @Description: 即时通讯服务门面
 * @Author: LIULJ
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
@Component
@Slf4j
public class InstantServer implements CommandLineRunner {

    private final WebSocketServer webSocketServer;

    @Getter
    @Autowired
    private RedisTemplate redisTemplate;
    @Getter
    private HandshakeCheckTimer handshakeCheckTimer;
    @Getter
    private ConnectionRegistry connectionRegistry;
    @Getter
    @Autowired
    private ConnectionRegistryRpcService connectionRegistryRpcService;
    @Getter
    private final TopicListenerContainer listenerCallbackMap;
    @Getter
    @Autowired
    private PushService messageService;

    public InstantServer() {
        connectionRegistry = new ClusterRedisConnectionRegistry(this);
        listenerCallbackMap = new TopicListenerContainer(this);
        listenerCallbackMap.add(new DefaultTopicListener(this));
        //初始化cocket 移动端
        this.webSocketServer = new WebSocketServer(this);
        handshakeCheckTimer = new HandshakeCheckTimer(this);
    }

    /**
     * 发送至集群
     * @param message
     */
    public void publishConnectorMessage(PushMessage message){
        redisTemplate.convertAndSend(InstantConfig.server.jmx.topic,message);
    }

    /**
     * 通知所有监听
     *
     * @param message 消息体
     */
    public void notifyAll(PushMessage message) {
        if (message == null) {
            return;
        }
        listenerCallbackMap.notifyAll(message);
    }

    /**
     * 通知某个pattern的监听者
     *
     * @param pattern 通道
     * @param message 消息体
     */
    public void notify(String pattern, PushMessage message) {
        if (message == null) {
            return;
        }
        listenerCallbackMap.notify(pattern, message);
    }

    public void start() {
        log.info("server begin start at thread {}",Thread.currentThread().getName());
        log.info("begin init websocket server");
        this.webSocketServer.init();
        log.info("begin start websocket server");
        this.webSocketServer.start();
        //检测版权
        handshakeCheckTimer.start();
    }

    public void stop() {
        log.info("begin stop websocket server");
        this.webSocketServer.stop();
        log.info("stop websocket server success");
        handshakeCheckTimer.stop();
    }

    @Override
    public void run(String... args) throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                start();
            }
        },"instant-server-thread" + System.currentTimeMillis()).start();
    }

}
